using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Text;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace TweakSP.Web.Application
{
    public partial class TweakSP_GetPoSH : LayoutsPageBase
    {

        const string REQUESTMODE_SITE = "Site";
        const string REQUESTMODE_WEB = "Web";
        const string REQUESTMODE_LIST = "List";
        const string REQUESTMODE_PAGE = "Page";

        const string PARAM_LISTID = "LISTID";


        protected override void OnLoad(EventArgs e)
        {
            string requestMode = Request["REQUESTMODE"];
            string script = string.Empty;

            Response.Clear();
            Response.ContentType = "text/plain";

            switch (requestMode)
            {
                case REQUESTMODE_SITE:
                    script = GetSiteScript();
                    break;

                case REQUESTMODE_LIST:
                    string listId = Request[PARAM_LISTID];
                    script = GetListScript(listId);
                    break;

                default:
                    Response.Write("Unknown Request Mode<br />");
                    break;
            }

            if (string.IsNullOrEmpty(script))
            {
                Response.Write("Unable to render script<br />");
            }
            else
            {
                Response.Write(script);
            }

            Response.End();
        }

        private string GetSiteScript()
        {
            StringBuilder script = new StringBuilder();

            string webUrl = SPControl.GetContextWeb(Context).Url;

            script.AppendLine("[System.Reflection.Assembly]::LoadWithPartialName(\"Microsoft.SharePoint\")");
            script.AppendLine("$site = New-Object Microsoft.SharePoint.SPSite(\"" + webUrl + "\")");

            return script.ToString();
        }

        private string GetListScript(string listId)
        {
            StringBuilder script = new StringBuilder();

            SPWeb web = SPControl.GetContextWeb(Context);

            string webUrl = web.Url;

            script.AppendLine("[System.Reflection.Assembly]::LoadWithPartialName(\"Microsoft.SharePoint\")");
            script.AppendLine("$site = New-Object Microsoft.SharePoint.SPSite(\"" + webUrl + "\")");
            script.AppendLine("$web = $site.OpenWeb()");
            script.AppendLine("$guid = New-Object System.Guid(\"" + listId + "\")");
            script.AppendLine("$list = $web.Lists[$guid]");

            return script.ToString();
        }


    }
}
